import { configMap, createNamedStore } from "../../config/index.js"
import { waitForSelectorWithInterval, arrayToValueOfConfig, replacePlaceholder, closeUnwantedPages } from "../../utils/index.js"
import CryptoJS from "crypto-js"
import { getMaterial, handlePostException, sendFeiShuNotice } from "../../api/webApi/index.js"
export const fbPostingGroupCycleStore = createNamedStore("fb_posting_to_group_main")
// 添加一个常量用于存储被限制发帖的社群
const RESTRICTED_GROUPS_KEY = "restricted_groups_map"
// 账号被封了
const ACCOUNT_BLOCKED_KEY = "account_blocked_map"
// 添加一个常量表示限制天数（毫秒）
const RESTRICTION_PERIOD = 3 * 24 * 60 * 60 * 1000 // 3天

export const fb_posting_to_group_main = async (task, browser, index, taskId, postingGroupParams) => {
  // 账号是否被封
  let isAccountBlocked = false
  // 社群推广
  console.log("社群推广")
  const composedTask = task.composedTask
  // 当前策略的运行时间段
  const ranges = task?.operatingTimeRanges?.ranges || []
  console.log("fb_posting_to_group_main=ranges===>", ranges)
  // 创建结果对象
  const result = {
    success: false,
    message: "",
    taskId,
    postedGroupsCount: 0,
  }
  let finished = false
  // 已经处理过的文案不再处理。记录一下
  let isHandleList = []
  // 最后一条已处理过的小组
  let lastHandleGroup = null
  // 获取运行配置
  const config = composedTask.config || []
  // 获取运行周期  1每天运行一次  2每次任务时间段内执行一次
  const _runCycle = arrayToValueOfConfig(config, "execution_cycle")
  // 推广社群数量
  const _postingGroupCount = arrayToValueOfConfig(config, "posting_count")
  console.log("_postingGroupCount", _postingGroupCount)
  // 检查运行周期条件是否满足
  const accountId = task.platformAccount
  const cacheKey = `fb_posting_to_group_${accountId}`
  const lastCommentTime = fbPostingGroupCycleStore.get(cacheKey)
  console.log("lastCommentTime===>", lastCommentTime)
  const currentTime = Date.now()

  console.log(`当前运行周期: ${_runCycle === "1" ? "每天运行一次" : "每次任务时间段内执行一次"}`)

  // 判断是否满足运行条件
  const isSatisfiedRunCycle = await isInConditionsAsync(lastCommentTime, currentTime, ranges, fbPostingGroupCycleStore, cacheKey, _runCycle)
  if (isSatisfiedRunCycle) {
    console.log("跳过执行，原因：====>isSatisfiedRunCycle", isSatisfiedRunCycle)
    return
  }
  // 记录当前运行时间
  console.log(`满足运行条件，开始执行评论任务，更新运行时间: ${new Date(currentTime).toLocaleString()}`)

  // 转换评论内容
  console.log("task=>=====>", task)
  //  执行加入社群任务
  console.log("开始执行加入社群任务")
  // 获取素材数据
  let mediaUrls = []
  let postContent = ""
  // 获取主播id获取素材
  const mediaUrlRes = await getMaterial(
    {
      platformAccount: task.platformAccount,
      hostId: task.host.id,
      type: "promote",
    },
    {
      headers: {
        "X-Platform": task.platformName,
        "X-ScriptApp": "browser",
        "X-Device-Id": task.deviceId,
        "tenant-id": task.tenantId,
      },
    }
  )
  console.log("素材获取结果:", mediaUrlRes.data)
  postContent = mediaUrlRes.data?.content || ""
  const getInfo = mediaUrlRes.data?.list || []
  if (getInfo && getInfo.length > 0) {
    mediaUrls = getInfo.map((item) => item.url)
  }
  if (!postContent) {
    console.error("无效的帖子内容")
    return { success: false, message: "无效的帖子内容", taskId }
  }
  const context = browser.defaultBrowserContext()
  // 设置要允许的网站（注意：必须是 HTTPS）
  const targetUrl = "https://www.facebook.com"

  // 授予所有权限
  await context.overridePermissions(targetUrl, [
    "geolocation",
    "notifications",
    "midi",
    "camera",
    "microphone",
    "background-sync",
    "ambient-light-sensor",
    "accelerometer",
    "gyroscope",
    "magnetometer",
    "clipboard-read",
    "clipboard-write",
    "payment-handler",
  ])
  await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 10))
  await closeUnwantedPages(browser, ["www.facebook.com", "start.adspower.net"])
  const page = await browser.newPage()
  await page.setViewport({ width: 1920, height: 1080 })
  console.log("我进来找小组数据推广了！=====>")
  try {
    await page.goto(targetUrl, { waitUntil: "networkidle2" })
    await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 5))
    // 获取小组按钮
    const groupBtnSelector = ".x1iyjqo2 > div:nth-child(1) > ul > li div.x1sxyh0"
    // 等待左侧tab列表按钮出现
    await page.waitForSelector(groupBtnSelector, { timeout: 1000 * 10 })
    // 获取按钮列表。要可见的
    const groupBtns = await page.$$(groupBtnSelector)
    for (let index = 0; index < groupBtns.length; index++) {
      const groupBtn = groupBtns[index]
      // 可见的才点击
      if (await groupBtn.boundingBox()) {
        // 在判断是不是小组。
        const groupTitle = await groupBtn.evaluate((node) => node.textContent.trim())
        if (/小组|Groups|社團/.test(groupTitle)) {
          // 是小组。直接点击
          await groupBtn.click()
          console.log("点击小组按钮完成！！！")
        }
      }
    }
    await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 3))
    // 点击完毕。等待查看全部控件出现
    const myGroupListSelector = ".x1e56ztr > div > div:nth-child(3) > .x1i10hfl > .x6s0dn4"
    await page.waitForSelector(myGroupListSelector, { timeout: 1000 * 10 })
    const myGroupList = await page.$$(myGroupListSelector)
    for (let index = 0; index < myGroupList.length; index++) {
      const myGroup = myGroupList[index]
      // 获取myGroup的文案
      const myGroupText = await myGroup.evaluate((node) => node.textContent.trim())
      const box = await myGroup.boundingBox()
      if (box) {
        console.log("myGroupText=====>", myGroupText)
        console.log("box=======>", box)
        // 计算点击位置（元素中心）
        const x = box.x + box.width / 2
        const y = box.y + box.height / 2
        // 点击小组按钮
        myGroup && (await page.mouse.click(x, y, { delay: 100 }))
        console.log("点击小组完成！！！")
      }
    }
    // 等待小组列表出现
    const groupListSelector = 'div[class="x1jx94hy x1lq5wgf xgqcy7u x30kzoy x9jhf4c x1olyfxc x9f619 x78zum5 xdt5ytf x1qughib xyamay9 x1pi30zi x1l90r2v x1swvt13"]'
    await page.waitForSelector(groupListSelector, { timeout: 1000 * 10 })
    while (!finished) {
      await new Promise((resolve) => setTimeout(resolve, 1000 * 3))
      let groupList = await page.$$(groupListSelector)
      // 获取可见的列表
      let visibleGroupList = []
      for (let index = 0; index < groupList.length; index++) {
        const groupItem = groupList[index]
        if (await groupItem.boundingBox()) {
          visibleGroupList.push(groupItem)
        }
      }
      console.log("visibleGroupList===>", visibleGroupList)
      // 遍历可见的列表进行操作
      for (let index = 0; index < visibleGroupList.length; index++) {
        // 每次变量都要看看账号是否被封
        if (isAccountBlocked) {
          // 账号被封。
          console.log("账号被封，跳过执行")
          finished = true
          return { success: false, message: "账号被封，跳过执行", taskId }
        }
        const visibleGroupItem = visibleGroupList[index]
        console.log("visibleGroupItem=====>", visibleGroupItem)
        // 小组昵称
        const groupNickNameSelector = "div.x8gbvx8 > div a.xt0psk2"
        // 查看小组
        const groupViewSelector = "div.x8gbvx8 > div div.xn6708d"
        // 获取里面昵称文本
        const groupNickNameElement = await visibleGroupItem.$(groupNickNameSelector)
        const groupNickName = await groupNickNameElement.evaluate((node) => node.textContent.trim())
        console.log("groupNickName=====>", groupNickName)
        console.log("isHandleList.length=====>", isHandleList.length)
        console.log("visibleGroupList.length=====>", visibleGroupList.length)
        console.log("_postingGroupCount=====>", _postingGroupCount)
        // 如果当前处理的数量大于配置数量直接跳过
        if (isHandleList.length >= _postingGroupCount || (visibleGroupList.length <= _postingGroupCount && isHandleList.length >= visibleGroupList.length)) {
          console.log("已经处理的数量大于配置数量，跳过执行")
          finished = true
          break
        }
        // 判断是否处理过。已处理过的不在处理
        if (isHandleList.includes(groupNickName)) {
          console.log("跳过处理，原因：====>isHandleList", isHandleList)
          continue
        }
        isHandleList.push(groupNickName)
        // 检查该社群是否在限制列表中
        const restrictedGroups = fbPostingGroupCycleStore.get(RESTRICTED_GROUPS_KEY) || {}
        const currentTime = Date.now()

        if (restrictedGroups[groupNickName]) {
          const restrictionStartTime = restrictedGroups[groupNickName]
          const timeElapsed = currentTime - restrictionStartTime

          if (timeElapsed < RESTRICTION_PERIOD) {
            // 如果限制时间未到，跳过该社群
            const remainingDays = Math.ceil((RESTRICTION_PERIOD - timeElapsed) / (24 * 60 * 60 * 1000))
            console.log(`社群 ${groupNickName} 在限制期内，还需等待 ${remainingDays} 天，跳过处理`)
            continue
          } else {
            // 如果限制时间已到，从限制列表中移除
            console.log(`社群 ${groupNickName} 限制期已过，从限制列表中移除`)
            delete restrictedGroups[groupNickName]
            fbPostingGroupCycleStore.set(RESTRICTED_GROUPS_KEY, restrictedGroups)
          }
        }
        if (lastHandleGroup != groupNickName) {
          console.log("lastHandleGroup=====>", lastHandleGroup)
          lastHandleGroup = groupNickName
        } else {
          // 如果当前处理的和最后一条是相同的。表示已经没有更多了。完成
          console.log("已经没有更多了")
          finished = true
          break
        }
        console.log("已经处理过的：", isHandleList)
        // 记录打开新标签页前的滚动位置
        const beforeNewPageScrollPosition = await page.evaluate(() => window.scrollY)
        // 获取查看小组按钮
        const groupViewBtn = await visibleGroupItem.$(groupViewSelector)
        // 获取groupViewBtn的文案
        const groupViewBtnText = await groupViewBtn.evaluate((node) => node.textContent.trim())
        console.log("groupViewBtnText=====>", groupViewBtnText)
        // 如果文案不为查看小组、View group、查看社團直接跳过
        if (!/查看小组|View group|查看社團/.test(groupViewBtnText)) {
          console.log("跳过处理，原因：====>groupViewBtnText", groupViewBtnText)
          continue
        }
        console.log("groupViewBtn=====>", groupViewBtn)
        // 点击查看小组按钮
        if (groupViewBtn) {
          // 使用ctrl+鼠标左键点击。开启新页面
          const newPage = await clickAndWaitForNewPage(browser, page, groupViewBtn)
          if (newPage) {
            console.log("新页面已打开")
          } else {
            console.log("新页面创建失败或超时")
          }
          try {
            // 检查新页面是否成功创建
            if (!newPage) {
              console.log("新页面创建失败，跳过当前帖子")
              // 安全关闭新页面，防止页面未打开导致错误
              try {
                if (newPage && !newPage.isClosed()) {
                  await newPage.close()
                  // 确保将焦点切回主页面，但保持滚动位置
                  await page.bringToFront()
                  // 恢复之前的滚动位置
                  await page.evaluate((position) => {
                    window.scrollTo({
                      top: position,
                      behavior: "instant", // 使用 instant 而不是 smooth 来避免滚动动画
                    })
                  }, beforeNewPageScrollPosition)
                }
              } catch (error) {
                console.error("关闭新页面发生错误:", error.message)
                // 错误不影响主流程，继续执行
              }
              continue
            }
            // 等待新页面加载完成
            await newPage.waitForSelector("body") // 等待 body 加载完成
            // 切换到新页面
            await newPage.bringToFront() // 将新页面带到前端

            // 等待页面完全加载
            await new Promise((resolve) => setTimeout(resolve, 3000))

            // 点击"写帖子"按钮打开发帖框
            const writePostButtonSelector = ".xkjl1po > .x1lliihq"
            await newPage.waitForSelector(writePostButtonSelector, { timeout: 10000 })
            // 获取按钮的坐标
            const writePostButton = await newPage.$(writePostButtonSelector)
            console.log("writePostButton====>", writePostButton)
            const writePostButtonBox = await writePostButton.boundingBox()
            if (writePostButtonBox) {
              const x = writePostButtonBox.x + writePostButtonBox.width / 2
              const y = writePostButtonBox.y + writePostButtonBox.height / 2
              await newPage.mouse.click(x, y, { delay: 100 })
              console.log("点击写帖子按钮")
            }
            // // 准备上传媒体文件
            // const mediaUrls = postingGroupParams.mediaUrls || [
            //   "https://ai-usa.oss-us-west-1.aliyuncs.com/bo/asset-lib/7ee2f38c-87d9-4e64-8172-443f68478691.mp4",
            //   "https://ai-usa.oss-us-west-1.aliyuncs.com/bo/asset-lib/c49f9467-ad6e-4574-bd38-f8e6d4e02107.jpg",
            // ]
            // 等待发帖对话框出现
            await new Promise((resolve) => setTimeout(resolve, 5000))
            // 等待媒体上传按钮出现
            const mediaButtonSelector = 'div[aria-label="Photo/video"]'
            const mediaButtonSelector2 = 'div[aria-label="照片/视频"]'
            const mediaButtonSelector3 = 'div[aria-label="相片／影片"'
            const imgSelector = 'img[class="x1b0d499 xl1xv1r"]'
            // 点击媒体上传按钮
            const mediaButton = (await newPage.$(mediaButtonSelector)) || (await newPage.$(mediaButtonSelector2)) || (await newPage.$(mediaButtonSelector3)) || (await newPage.$(imgSelector))
            if (mediaButton) {
              await new Promise((resolve) => setTimeout(resolve, 5000))
              await newPage.keyboard.press("Backspace")
              // 输入文本
              await newPage.keyboard.type(replacePlaceholder(postContent, configMap, task))
              console.log("成功输入文本")
              // <input  class="x1s85apg" type="file">
              // 通过父元素获取文件输入框
              let fileInput = await newPage.$('input[type="file"].x1s85apg[multiple]')
              console.log("fileInput=====>1111", fileInput)
              // 并且可见在视图中
              const fileInputBox = fileInput ? await fileInput.boundingBox() : null
              console.log("fileInputBox=====>", fileInputBox)
              if (!fileInput) {
                // file不存在直接点击一下图片
                await mediaButton.click()
                await new Promise((resolve) => setTimeout(resolve, 5000))
                console.log("点击了媒体上传按钮")
                // 重新获取
                fileInput = await newPage.$('input[type="file"].x1s85apg[multiple]')
              }
              console.log("fileInput=====>", fileInput)
              console.log("mediaUrls=====>", mediaUrls)
              if (fileInput) {
                await uploadMedia(newPage, browser, mediaUrls)
                console.log("媒体文件上传完成")
              }
            }
            // 等待上传完成
            await new Promise((resolve) => setTimeout(resolve, 5000))

            // 点击发布按钮
            const postButtonSelector = 'div[aria-label="Post"]'
            const postButtonSelector1 = 'div[aria-label="發佈"]'
            const postButtonSelector2 = 'div[aria-label="发布"]'
            const postButton = (await newPage.$(postButtonSelector)) || (await newPage.$(postButtonSelector1)) || (await newPage.$(postButtonSelector2))

            if (postButton) {
              await postButton.click()
              console.log("点击发布按钮")

              // 等待发布完成
              await new Promise((resolve) => setTimeout(resolve, 8000))
              let successCheck = false
              // 检查发布是否成功
              // 检查俩分钟。div[role="dialog"]不见了。那就是发生成功，否则直接失败
              let findCount = 0
              while (!successCheck) {
                findCount = findCount + 1
                console.log("findCount=====>", findCount)
                if (findCount >= 60) {
                  console.log("发布超时")
                  successCheck = false
                  // 如果发布超时。我们寻找一下限制提示
                  const restrictionSelector = 'div[class="x1hkcv85 xw2csxc x1odjw0f x1n2onr6"]'
                  // 等待元素出现
                  await newPage.waitForSelector(restrictionSelector, { timeout: 10000 })
                  const restriction = await newPage.$(restrictionSelector)
                  if (restriction) {
                    // 如果存在限制提示。说明社群暂停发帖
                    const restrictionText = await restriction.evaluate((node) => node.textContent.trim())
                    console.log("restrictionText=====>", restrictionText)
                    // 社群暂停发帖--限制三天
                    // 将社群添加到限制列表中
                    let accountBlocked = Date.now()
                    fbPostingGroupCycleStore.set(ACCOUNT_BLOCKED_KEY, accountBlocked)
                    console.log(`社群 ${groupNickName} 发布失败，已添加到限制列表，该业务账号${task.platformAccount}将在3天后再次尝试`)
                    isAccountBlocked = true
                    // 限制三天之后发送飞书通知给后台
                    // 构建参数
                    const bandParams = {
                      platformAccount: task.platformAccount,
                      operatorName: task.host?.name,
                      reason: `fb社群推广发帖被平台临时限制`,
                      deviceId: task.deviceId,
                      code: 5,
                    }
                    console.log("bandParams=====>", bandParams)
                    const handleSendBandRes = await sendFeiShuNotice(bandParams, {
                      headers: {
                        "X-Platform": task.platformName,
                        "X-Device-Id": task.deviceId,
                        "X-ScriptApp": "browser",
                        "tenant-id": task.tenantId,
                        "Content-Type": "application/x-www-form-urlencoded",
                      },
                    })
                    console.log("handleSendBandRes====>", handleSendBandRes)
                  }
                  break
                }
                // 定时检查div[role="dialog"]俩分钟
                const dialogSelector =
                  'div[class="x1n2onr6 x1ja2u2z x1afcbsf x78zum5 xdt5ytf x1a2a7pz x6ikm8r x10wlt62 x71s49j x1jx94hy x1qpq9i9 xdney7k xu5ydu1 xt3gfkd x104qc98 x1g2kw80 x16n5opg xl7ujzl xhkep3z x193iq5w"]'
                const dialog = await newPage.$(dialogSelector, { visible: true })
                if (!dialog) {
                  successCheck = true
                  console.log("发布成功")
                  break
                }
                await new Promise((resolve) => setTimeout(resolve, 1000))
              }

              if (successCheck) {
                console.log("发布成功")
                result.success = true
                result.message = "发布成功"
                // 查看更多按钮
                const viewMoreSelector = ".x9f619:nth-child(2) > .x1n2onr6 > .x1i10hfl > .x1ja2u2z"
                const viewMoreBtns = await newPage.$$(viewMoreSelector)
                // 点击进入
                for (let index = 0; index < viewMoreBtns.length; index++) {
                  const viewMoreBtn = viewMoreBtns[index]
                  if (viewMoreBtn && (await viewMoreBtn.boundingBox())) {
                    viewMoreBtn && (await viewMoreBtn.click())
                    console.log("点击查看更多按钮")
                    await new Promise((resolve) => setTimeout(resolve, 5000))
                    //获取你的内容。并点击进去
                    const elementHandle = await newPage.evaluateHandle(() => {
                      const anchors = Array.from(document.querySelectorAll("a"))
                      const regex = /\/groups\/[^/]+\/my_pending_content\//
                      const match = anchors.find((a) => regex.test(a.getAttribute("href")))
                      return match || null
                    })
                    if (elementHandle) {
                      try {
                        await new Promise((resolve) => setTimeout(resolve, 5000))
                        await elementHandle.click()
                        console.log("点击你的内容按钮")
                        await new Promise((resolve) => setTimeout(resolve, 5000))
                        // 等待已发布的出现
                        const publishedSelector = ".xb57i2i > .x78zum5 > .x1xmf6yo > div div.x1r8uery"
                        await newPage.waitForSelector(publishedSelector, { timeout: 10000 })
                        const publishedBtns = await newPage.$$(publishedSelector)
                        console.log("publishedBtns=====>", publishedBtns)
                        for (let index = 0; index < publishedBtns.length; index++) {
                          console.log("await publishedBtns[index].evaluate((node) => node.textContent.trim())", await publishedBtns[index].evaluate((node) => node.textContent.trim()))
                          // 遍历出文本为：已发布、Published的元素并点击
                          if (/Published|已发布|已發佈/.test(await publishedBtns[index].evaluate((node) => node.textContent.trim()))) {
                            await publishedBtns[index].click()
                            // 获取按钮的坐标
                            const publishedBtnBox = await publishedBtns[index].boundingBox()
                            if (publishedBtnBox) {
                              const x = publishedBtnBox.x + publishedBtnBox.width / 2
                              const y = publishedBtnBox.y + publishedBtnBox.height / 2
                              await newPage.mouse.click(x, y, { delay: 100 })
                              console.log("点击已发布按钮")
                            }
                            await new Promise((resolve) => setTimeout(resolve, 2000))
                            // 等待帖子详情出现
                            const postDetailSelector = "div.x1e56ztr:nth-child(2) > div"
                            await newPage.waitForSelector(postDetailSelector, { timeout: 10000 })
                            const postDetailBtns = await newPage.$$(postDetailSelector)
                            // 如果没有也是发布失败
                            if (postDetailBtns.length === 0) {
                              console.log("发布失败")
                              // 这个社群暂停三天发帖
                              // 将社群添加到限制列表中
                              const restrictedGroups = fbPostingGroupCycleStore.get(RESTRICTED_GROUPS_KEY) || {}
                              restrictedGroups[groupNickName] = currentTime
                              fbPostingGroupCycleStore.set(RESTRICTED_GROUPS_KEY, restrictedGroups)
                              console.log(`社群 ${groupNickName} 发布失败，已添加到限制列表，将在3天后解除限制`)
                            } else {
                              for (let index = 0; index < postDetailBtns.length; index++) {
                                // 可见的帖子的第一个帖子
                                if (postDetailBtns[index] && (await postDetailBtns[index].boundingBox())) {
                                  // 获取元素里面所有的文本
                                  const postDetailText = await postDetailBtns[index].evaluate((node) => node.textContent.trim())
                                  console.log("postDetailText=====>", postDetailText)
                                  // 如果第一条的文本内容包含了我们的配置文本内容。则表示发布成功
                                  console.log("replacePlaceholder(postContent)==>", replacePlaceholder(postContent, configMap, task))
                                  if (postDetailText.includes(replacePlaceholder(postContent, configMap, task))) {
                                    console.log("发布成功")
                                    break
                                  } else {
                                    console.log("发布失败")
                                    // 这个社群暂停三天发帖
                                    // 将社群添加到限制列表中
                                    const restrictedGroups = fbPostingGroupCycleStore.get(RESTRICTED_GROUPS_KEY) || {}
                                    restrictedGroups[groupNickName] = currentTime
                                    fbPostingGroupCycleStore.set(RESTRICTED_GROUPS_KEY, restrictedGroups)
                                    console.log(`社群 ${groupNickName} 发布失败，已添加到限制列表，将在3天后解除限制`)
                                    break
                                  }
                                } else {
                                  console.log("发布失败")
                                  // 这个社群暂停三天发帖
                                  // 将社群添加到限制列表中
                                  const restrictedGroups = fbPostingGroupCycleStore.get(RESTRICTED_GROUPS_KEY) || {}
                                  restrictedGroups[groupNickName] = currentTime
                                  fbPostingGroupCycleStore.set(RESTRICTED_GROUPS_KEY, restrictedGroups)
                                  console.log(`社群 ${groupNickName} 发布失败，已添加到限制列表，将在3天后解除限制`)
                                  break
                                }
                              }
                            }
                          }
                        }
                      } catch (error) {
                        console.log("发布失败", error)
                        const restrictedGroups = fbPostingGroupCycleStore.get(RESTRICTED_GROUPS_KEY) || {}
                        restrictedGroups[groupNickName] = currentTime
                        fbPostingGroupCycleStore.set(RESTRICTED_GROUPS_KEY, restrictedGroups)
                        console.log(`社群 ${groupNickName} 发布失败，已添加到限制列表，将在3天后解除限制`)
                      }
                    }
                    break
                  }
                }
              } else {
                console.log("发布可能失败")
                result.success = false
                result.message = "发布失败"
              }
            }

            // 安全关闭新页面，防止页面未打开导致错误
            try {
              if (newPage && !newPage.isClosed()) {
                await newPage.close()
                // 确保将焦点切回主页面，但保持滚动位置
                await page.bringToFront()
                // 恢复之前的滚动位置
                await page.evaluate((position) => {
                  window.scrollTo({
                    top: position,
                    behavior: "instant", // 使用 instant 而不是 smooth 来避免滚动动画
                  })
                }, beforeNewPageScrollPosition)
              }
            } catch (error) {
              console.error("关闭新页面发生错误:", error.message)
              // 错误不影响主流程，继续执行
            }

            await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 2))
          } catch (error) {
            // 安全关闭新页面，防止页面未打开导致错误
            try {
              if (newPage && !newPage.isClosed()) {
                await newPage.close()
                // 确保将焦点切回主页面，但保持滚动位置
                await page.bringToFront()
                // 恢复之前的滚动位置
                await page.evaluate((position) => {
                  window.scrollTo({
                    top: position,
                    behavior: "instant", // 使用 instant 而不是 smooth 来避免滚动动画
                  })
                }, beforeNewPageScrollPosition)
              }
            } catch (error) {
              console.error("关闭新页面发生错误:", error.message)
              // 错误不影响主流程，继续执行
            }
          }
        }
        // 每一轮循环等待俩秒
        await new Promise((resolve) => setTimeout(resolve, 1000 * 2))
      }
    }
  } catch (error) {
    console.error("发帖任务执行失败:", error.message)
    result.success = false
    result.message = `发帖失败: ${error.message}`
    // 处理发帖异常
    const params = {
      hostAssetId: getInfo ? getInfo[0]?.folderId : "",
      hostAssetRecordId: getInfo ? getInfo[0]?.hostAssetRecordId : "",
      accountId: task.platformAccount,
      operatorName: task.host.name,
      errorMessage: "测试回滚",
      deviceId: task.deviceId,
    }
    const handlePostExceptionRes = await handlePostException(params, {
      headers: {
        "X-Platform": task.platformName,
        "X-Device-Id": task.deviceId,
        "X-ScriptApp": "browser",
        "tenant-id": task.tenantId,
        "Content-Type": "application/x-www-form-urlencoded",
      },
    })
    console.log("处理发帖异常结果:", handlePostExceptionRes)
    console.log("加入社群任务失败", error) // 删除本地时间戳缓存
    fbPostingGroupCycleStore.delete(cacheKey)
  } finally {
    // 关闭页面
    if (page && !page.isClosed()) {
      await page.close()
    }
  }
}

/**
 * 异步判断是否在运行条件中
 * @param {number} lastCommentTime 上次运行时间
 * @param {number} currentTime 当前时间
 * @param {Array} ranges 时间段数组（仅 _runCycle === "2" 时需要）
 * @param {object} fbPostingGroupCycleStore 本地缓存操作对象
 * @param {string} cacheKey 缓存键
 * @param {string} _runCycle 运行周期 "1"=每天, "2"=时间段
 * @param {boolean} onlyCheck 是否只判断不写入缓存，默认 false
 * @returns {Promise<false | string | true>}
 */
export async function isInConditionsAsync(lastCommentTime, currentTime, ranges, fbPostingGroupCycleStore, cacheKey, _runCycle, onlyCheck = false) {
  if (lastCommentTime) {
    const lastTimeObj = new Date(lastCommentTime)
    console.log(`上次评论时间: ${lastTimeObj.toLocaleString()}`)

    if (_runCycle === "1") {
      const hoursPassed = (currentTime - lastCommentTime) / (1000 * 60 * 60)
      console.log(`距离上次评论已经过去 ${hoursPassed.toFixed(2)} 小时`)

      if (hoursPassed < 24) {
        const msg = `未到达每日评论周期，还需等待 ${(24 - hoursPassed).toFixed(2)} 小时`
        console.log(msg)
        return msg
      } else {
        console.log("每日运行条件通过")
        if (!onlyCheck) {
          console.log("更新本地缓存中的最后评论时间")
          fbPostingGroupCycleStore.set(cacheKey, currentTime)
        }
        return false
      }
    }

    if (_runCycle === "2") {
      const lastDate = lastTimeObj.toLocaleDateString()
      const currentDate = new Date().toLocaleDateString()
      const lastHour = lastTimeObj.getHours()
      const lastMinute = lastTimeObj.getMinutes()
      const currentHour = new Date().getHours()
      const currentMinute = new Date().getMinutes()

      const getCurrentTimeSlot = (hour, minute) => {
        const currentTotalMinutes = hour * 60 + minute
        if (!ranges || ranges.length === 0) {
          return `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`
        }

        for (const range of ranges) {
          const [startHour, startMinute] = range.startTime.split(":").map(Number)
          const [endHour, endMinute] = range.endTime.split(":").map(Number)
          const startTotalMinutes = startHour * 60 + startMinute
          const endTotalMinutes = endHour * 60 + endMinute

          if (currentTotalMinutes >= startTotalMinutes && currentTotalMinutes <= endTotalMinutes) {
            return `${range.startTime}-${range.endTime}`
          }
        }

        const fallback = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`
        console.log(`当前时间 ${fallback} 不在任何时间段内`)
        return fallback
      }

      const lastSlot = getCurrentTimeSlot(lastHour, lastMinute)
      const currentSlot = getCurrentTimeSlot(currentHour, currentMinute)

      console.log(`上次时间段: ${lastDate} ${lastSlot}, 当前时间段: ${currentDate} ${currentSlot}`)

      if (lastDate === currentDate && lastSlot === currentSlot) {
        const msg = `当前时间段 (${currentSlot}) 已执行过评论任务，等待下一个时间段`
        console.log(msg)
        return msg
      } else {
        console.log("时间段模式条件通过")
        if (!onlyCheck) {
          console.log("更新本地缓存中的最后评论时间")
          fbPostingGroupCycleStore.set(cacheKey, currentTime)
        }
        return false
      }
    }

    return true // 未知运行周期
  } else {
    console.log("首次运行评论任务，无需检查周期")
    if (!onlyCheck) {
      fbPostingGroupCycleStore.set(cacheKey, currentTime)
    }
    return false
  }
}
async function scrollToBottom(step = 100, page) {
  const scrollResult = await page.evaluate(async (step) => {
    const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

    // 获取滚动前的位置
    const beforeScrollY = window.scrollY
    console.log("滚动前位置:", beforeScrollY)

    // 计算合理的滚动步长
    const scrollStep = step + Math.random() * step * 0.5 // 每次滚动 100-150px，减小随机性
    const scrollDelay = 50 + Math.random() * 100 // 每次滚动间隔 50-150ms，更流畅

    // 使用相对滚动，从当前位置滚动一定距离，而不是绝对位置
    window.scrollBy({
      top: scrollStep,
      behavior: "smooth", // 使用平滑滚动
    })

    await delay(scrollDelay)

    // 模拟偶尔停顿，但减少概率
    if (Math.random() < 0.1) {
      const pauseTime = 500 + Math.random() * 1000 // 0.5-1.5秒的停顿，缩短停顿时间
      await delay(pauseTime)
    }

    // 获取滚动后的位置，并确认滚动是否有效
    const afterScrollY = window.scrollY
    console.log("滚动后位置:", afterScrollY)

    // 计算滚动是否有效（是否真的向下滚动了）
    const scrolledEffectively = afterScrollY > beforeScrollY

    // 判断是否到底部
    const reachedBottom = document.documentElement.scrollTop + window.innerHeight >= document.documentElement.scrollHeight - 10 // 添加10px的容差

    return {
      reachedBottom,
      scrolledEffectively,
      beforePosition: beforeScrollY,
      afterPosition: afterScrollY,
    }
  }, step)

  // 记录滚动结果
  console.log(`滚动结果: 到达底部=${scrollResult.reachedBottom}, 有效滚动=${scrollResult.scrolledEffectively}, 位置变化=${scrollResult.beforePosition} -> ${scrollResult.afterPosition}`)

  // 如果滚动无效，可以认为已经到底
  if (!scrollResult.scrolledEffectively) {
    console.log("滚动无效，可能已经到底或遇到阻碍")
  }

  return scrollResult.reachedBottom
}
/**
 * 上传媒体文件（一次性）
 * @param {Page} page - Puppeteer页面实例
 * @param {Browser} browser - Puppeteer浏览器实例
 * @param {string[]} mediaUrls - 媒体URL列表
 */
async function uploadMedia(page, browser, mediaUrls) {
  try {
    const axios = await import("axios")
    const fs = await import("fs")
    const path = await import("path")
    const os = await import("os")

    const fileInput = await page.$('input[type="file"].x1s85apg[multiple]')
    if (!fileInput) throw new Error("找不到文件上传输入框")

    const tempFilePaths = []

    for (let index = 0; index < mediaUrls.length; index++) {
      const mediaUrl = mediaUrls[index]
      console.log(`正在下载媒体文件: ${mediaUrl}`)

      const isVideo = mediaUrl.toLowerCase().endsWith(".mp4") || mediaUrl.toLowerCase().includes("video")
      const fileName = isVideo ? `temp_video_${index}.mp4` : `temp_image_${index}.jpg`
      const tempFilePath = path.join(os.tmpdir(), fileName)

      try {
        const response = await axios.default.get(mediaUrl, {
          responseType: "arraybuffer",
          headers: {
            "User-Agent": "Mozilla/5.0",
            Referer: "https://www.facebook.com",
          },
          timeout: 60000,
        })

        fs.writeFileSync(tempFilePath, Buffer.from(response.data))
        console.log(`下载完成: ${tempFilePath}`)
        tempFilePaths.push(tempFilePath)
      } catch (error) {
        console.error(`下载失败: ${error.message}`)
        throw error
      }
    }

    // 一次性上传所有文件
    console.log("开始上传所有文件...")
    await fileInput.uploadFile(...tempFilePaths)
    console.log("文件上传完成")

    // 等待上传完成
    await new Promise((resolve) => setTimeout(resolve, 8000))

    // 删除所有临时文件
    for (const filePath of tempFilePaths) {
      try {
        fs.unlinkSync(filePath)
        console.log(`已删除临时文件: ${filePath}`)
      } catch (e) {
        console.error(`删除临时文件失败: ${e.message}`)
      }
    }
  } catch (error) {
    console.error("上传媒体文件时出错:", error)
    throw error
  }
}
// ctrl+点击开启一个新的页面
async function clickAndWaitForNewPage(browser, page, groupViewBtn, timeout = 10000) {
  try {
    // 先记录已有的 target 数量
    const existingTargetIds = new Set(browser.targets().map((t) => t._targetId))

    // 创建一个等待新页面的 Promise（使用 waitForTarget 更稳）
    const newPagePromise = new Promise((resolve) => {
      const timer = setTimeout(() => {
        console.log("等待新页面创建超时")
        resolve(null)
      }, timeout)

      browser.on("targetcreated", async (target) => {
        if (!existingTargetIds.has(target._targetId) && target.type() === "page") {
          const newPage = await target.page()
          clearTimeout(timer)
          resolve(newPage)
        }
      })
    })

    // 执行点击操作
    console.log("Control===1")
    await new Promise((r) => setTimeout(r, 2000))

    const initialBox = await groupViewBtn.boundingBox()
    await new Promise((r) => setTimeout(r, 500))
    const finalBox = await groupViewBtn.boundingBox()

    if (initialBox && finalBox && initialBox.x === finalBox.x && initialBox.y === finalBox.y) {
      console.log("Element is stable")
    }

    await page.evaluate((el) => el.scrollIntoView({ behavior: "smooth", block: "center" }), groupViewBtn)
    await new Promise((r) => setTimeout(r, 500))

    const box = await groupViewBtn.boundingBox()
    if (!box) throw new Error("Element not found or not visible")

    const x = box.x + box.width / 2
    const y = box.y + box.height / 2

    await page.keyboard.down("Control")
    console.log("Control===2")
    await new Promise((r) => setTimeout(r, 100))

    await page.mouse.click(x, y, { delay: 100 })
    console.log("Control===3")
    await new Promise((r) => setTimeout(r, 100))

    await page.keyboard.up("Control")
    await new Promise((r) => setTimeout(r, 1000))

    const newPage = await newPagePromise
    return newPage
  } catch (err) {
    console.error("点击并等待新页面时出错:", err)
    return null
  }
}
/**
 * 判断当前时间是否超过指定时间戳加三天，并返回剩余小时数
 * @param {number} timestamp - 目标时间戳（单位：毫秒）
 * @returns {{ isOver: boolean, hoursLeft: number }} - 是否超过，和还差多少小时（如果已超过则为 0）
 */
export function checkThreeDaysLater(timestamp) {
  const THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1000
  const targetTime = timestamp + THREE_DAYS_MS
  const now = Date.now()

  if (now > targetTime) {
    return { isOver: true, hoursLeft: 0 }
  } else {
    const msLeft = targetTime - now
    const hoursLeft = Math.ceil(msLeft / (60 * 60 * 1000)) // 向上取整
    return { isOver: false, hoursLeft }
  }
}
